package com.learn.core.controller.learn;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.JwtUtil;
import com.learn.common.utils.PageResult;
import com.learn.common.utils.ResultUtil;
import com.learn.common.utils.StringUtils;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.*;
import com.learn.core.domain.view.LevelSonUser;
import com.learn.core.domain.view.UserDetailsGather;
import com.learn.core.dto.LCompetitionSortDTO;
import com.learn.core.dto.LLevelDTO;
import com.learn.core.service.*;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.logging.Level;

/**
 * Description
 *
 * @author zhaohongyu
 * @ClassName LevelController
 * @date 2021.07.29 15:58
 * @describe 闯关模块
 */
@Api("闯关模块")
@RestController
@RequestMapping("/learn/level")
public class LevelController extends WebController<Level> {
    @Autowired
    private ILCompetitionSortService ilCompetitionSortService;
    @Autowired
    private ILLevelService ilLevelService;
    @Autowired
    private ILLevelSonService ilLevelSonService;
    @Autowired
    private ILLevelPaperService ilLevelPaperService;
    @Autowired
    private ILevelSonUserService iLevelSonUserService;
    @Autowired
    private ILLevelUserService ilLevelUserService;
    @Autowired
    private ILLevelSonUserService ilLevelSonUserService;
    @Autowired
    private ILUserService ilUserService;
    @Autowired
    private ILQuestionsService ilQuestionsService;
    @Autowired
    private ILOptionService ilOptionService;
    @Autowired
    private ILLevelAnswerService ilLevelAnswerService;
    @Autowired
    private ILLevelQuestionsService ilLevelQuestionsService;

    //分类列表
    @ApiOperation(value = "分类列表")
    @UserLoginToken
    @PostMapping("/sortList")
    public PageResult<LCompetitionSort> sortList(@RequestBody LCompetitionSortDTO lCompetitionSortDTO){
        try {
            if (lCompetitionSortDTO==null||lCompetitionSortDTO.getPage()==null||lCompetitionSortDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lCompetitionSortDTO.getPage(),lCompetitionSortDTO.getRows());
            QueryWrapper<LCompetitionSort> queryWrapper = new QueryWrapper<LCompetitionSort>();
            if(lCompetitionSortDTO.getParentNode()!=null)
                queryWrapper.eq("parent_node",lCompetitionSortDTO.getParentNode());
            else {
                queryWrapper.eq("parent_node","0");
            }
            if(lCompetitionSortDTO.getCompetitionSortName()!=null)
                queryWrapper.like("competition_sort_name",lCompetitionSortDTO.getCompetitionSortName());
            Page<LCompetitionSort> lCompetitionSorts = (Page<LCompetitionSort>) ilCompetitionSortService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lCompetitionSorts)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(lCompetitionSorts.getTotal(), lCompetitionSorts, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //关卡列表
    @ApiOperation(value = "关卡列表")
    @UserLoginToken()
    @PostMapping("/list")
    public PageResult<LLevel> list(@RequestBody LLevelDTO lLevelDTO, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if (lLevelDTO==null||lLevelDTO.getPage()==null||lLevelDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lLevelDTO.getPage(),lLevelDTO.getRows());
            QueryWrapper<LLevel> queryWrapper = new QueryWrapper<>();
            if(StringUtils.isNotEmpty(lLevelDTO.getSort()))
                queryWrapper.eq("competition_sort_id",lLevelDTO.getSort());
            queryWrapper.eq("state","1");
            queryWrapper.orderByAsc("level_num");
            Page<LLevel> levels = (Page<LLevel>)ilLevelService.list(queryWrapper);
            if (CollectionUtils.isEmpty(levels)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (LLevel level: levels) {
                QueryWrapper<LLevelUser> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("level_id",level.getLevelId());
                userQueryWrapper.eq("user_id",userId);
                LLevelUser lLevelUser = ilLevelUserService.getOne(userQueryWrapper);
                if(null != lLevelUser){
                    level.setUserState("1");
                }else {
                    level.setUserState("2");
                }
            }
            // 返回
            return new PageResult(levels.getTotal(), levels, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //小关卡列表
    @ApiOperation(value = "小关卡列表")
    @UserLoginToken()
    @PostMapping("/sonList")
    public PageResult<LLevelSon> sonList(@RequestBody LLevelDTO lLevelDTO, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if (lLevelDTO==null||lLevelDTO.getPage()==null||lLevelDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lLevelDTO.getPage(),lLevelDTO.getRows());
            QueryWrapper<LLevelSon> queryWrapper = new QueryWrapper<>();
            if(StringUtils.isNotEmpty(lLevelDTO.getId()))
                queryWrapper.eq("level_id",lLevelDTO.getId());
            queryWrapper.orderByAsc("level_num");
            Page<LLevelSon> levelSons = (Page<LLevelSon>)ilLevelSonService.list(queryWrapper);
            if (CollectionUtils.isEmpty(levelSons)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            for (LLevelSon son: levelSons) {
                QueryWrapper<LLevelSonUser> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("level_son_id",son.getLevelSonId());
                userQueryWrapper.eq("user_id",userId);
                LLevelSonUser lLevelSonUser = ilLevelSonUserService.getOne(userQueryWrapper);
                if(null != lLevelSonUser){
                    son.setUserId(userId);
                    son.setState(lLevelSonUser.getState());
                    son.setUserScore(lLevelSonUser.getUserScore());
                }
            }
            // 返回
            return new PageResult(levelSons.getTotal(), levelSons, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //关卡详情
    @ApiOperation(value = "关卡详情")
    @UserLoginToken
    @GetMapping("/levelInfo")
    public CommonResult<Object> levelInfo(@RequestParam("id")Integer id, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            // 关卡问题
            QueryWrapper<LLevelPaper> paperQueryWrapper = new QueryWrapper<>();
            paperQueryWrapper.eq("level_son_id",id);
            LLevelPaper lLevelPaper = ilLevelPaperService.getOne(paperQueryWrapper);
            Map<String,Object> map = new HashMap<>();
            LUser lUser = ilUserService.getById(userId);
            map.put("user",lUser);
            map.put("levelPaperId",lLevelPaper.getLevelPaperId());
            Map<String,Object> questionMap = new HashMap<>();
            String question = lLevelPaper.getLevelQuestionsId();
            JSONObject json = JSONObject.fromObject(question);
            if(StringUtils.isNotEmpty(json.get("check"))){
                List<Integer> list = (List) json.get("check");
                List<LQuestions> lQuestionsList = new ArrayList<>();
                for (Integer integer : list) {
                    LQuestions lQuestions = ilQuestionsService.getById(integer);
                    if(null != lQuestions){
                        QueryWrapper<LOption> queryLOption = new QueryWrapper<LOption>();
                        queryLOption.eq("questions_id",lQuestions.getQuestionsId());
                        List<LOption> lOptionList = ilOptionService.list(queryLOption);
                        lQuestions.setlOptionList(lOptionList);
                    }
                    lQuestionsList.add(lQuestions);
                }
                questionMap.put("check",lQuestionsList);
            }
            if(StringUtils.isNotEmpty(json.get("judge"))){
                List<Integer> list = (List) json.get("judge");
                List<LQuestions> lQuestionsList = new ArrayList<>();
                for (Integer integer : list) {
                    LQuestions lQuestions = ilQuestionsService.getById(integer);
                    if(null != lQuestions){
                        QueryWrapper<LOption> queryLOption = new QueryWrapper<LOption>();
                        queryLOption.eq("questions_id",lQuestions.getQuestionsId());
                        List<LOption> lOptionList = ilOptionService.list(queryLOption);
                        lQuestions.setlOptionList(lOptionList);
                    }
                    lQuestionsList.add(lQuestions);
                }
                questionMap.put("judge",lQuestionsList);
            }
            if(StringUtils.isNotEmpty(json.get("radio"))){
                List<Integer> list = (List) json.get("radio");
                List<LQuestions> lQuestionsList = new ArrayList<>();
                for (Integer integer : list) {
                    LQuestions lQuestions = ilQuestionsService.getById(integer);
                    if(null != lQuestions){
                        QueryWrapper<LOption> queryLOption = new QueryWrapper<LOption>();
                        queryLOption.eq("questions_id",lQuestions.getQuestionsId());
                        List<LOption> lOptionList = ilOptionService.list(queryLOption);
                        lQuestions.setlOptionList(lOptionList);
                    }
                    lQuestionsList.add(lQuestions);
                }
                questionMap.put("radio",lQuestionsList);
            }
            map.put("questions",questionMap);
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }


    //个人答题情况
    @ApiOperation(value = "个人答题情况")
    @UserLoginToken
    @GetMapping("/userAnswer")
    public CommonResult<Object> userAnswer(@RequestParam("id")Integer id, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            QueryWrapper<LLevelAnswer> answerQueryWrapper = new QueryWrapper<LLevelAnswer>();
            answerQueryWrapper.eq("level_son_id",id);
            answerQueryWrapper.eq("user_id",userId);
            List<LLevelAnswer> lLevelAnswers = ilLevelAnswerService.list(answerQueryWrapper);
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lLevelAnswers);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }


    //答题
    @ApiOperation(value = "答题")
    @UserLoginToken
    @PostMapping("/saveAnswer")
    public CommonResult<Object> saveAnswer(@RequestBody LLevelAnswer lLevelAnswer, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            lLevelAnswer.setUserId(Integer.parseInt(userId));
            if(ilLevelAnswerService.save(lLevelAnswer))
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }


    //提交关卡
    @ApiOperation(value = "提交关卡")
    @UserLoginToken
    @GetMapping("/saveLevel")
    public CommonResult<Object> saveLevel(@RequestParam("id")Integer id, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            Map<String,Object> map = new HashMap();
            // 考试记录
            QueryWrapper<LLevelAnswer> answerQueryWrapper = new QueryWrapper<LLevelAnswer>();
            answerQueryWrapper.eq("level_son_id",id);
            answerQueryWrapper.eq("user_id",userId);
            List<LLevelAnswer> answerList = ilLevelAnswerService.list(answerQueryWrapper);
            int scores = 0;
            for (LLevelAnswer lLevelAnswer : answerList) {
                LQuestions lQuestions = ilQuestionsService.getById(lLevelAnswer.getQuestionsId());
                String [] answer = lQuestions.getQuestionsAnswer().split(",");
                String [] userAnswer =lLevelAnswer.getUserAnswer().split(",");
                if(StringUtils.equalsIgnoreOrder(answer,userAnswer)){
                    QueryWrapper<LLevelQuestions> questionQueryWrapper = new QueryWrapper<LLevelQuestions>();
                    questionQueryWrapper.eq("level_son_id",id);
                    questionQueryWrapper.eq("questions_type_id",lQuestions.getQuestionsType());
                    LLevelQuestions lLevelQuestions = ilLevelQuestionsService.getOne(questionQueryWrapper);
                    scores += Integer.parseInt(lLevelQuestions.getQuestionsFraction());
                }
            }
            // 关卡详情
            LLevelSon lLevelSon = ilLevelSonService.getById(id);
            QueryWrapper<LLevelSonUser> sonUserQueryWrapper = new QueryWrapper<LLevelSonUser>();
            sonUserQueryWrapper.eq("level_son_id",id);
            sonUserQueryWrapper.eq("user_id",userId);
            LLevelSonUser lLevelSonUser = ilLevelSonUserService.getOne(sonUserQueryWrapper);
            lLevelSonUser.setLevelSonId(id);
            lLevelSonUser.setUserId(Integer.parseInt(userId));
            lLevelSonUser.setUserScore(Integer.toString(scores));
            lLevelSonUser.setCreateTime(new Date());
            if(Integer.parseInt(lLevelSon.getLevelFraction()) <= scores){
                lLevelSonUser.setState("1");
                map.put("state","1");
                //  计算是否为最后一关，然后记录通过大关卡状态和关卡称号
                QueryWrapper<LLevelSon> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("level_id",lLevelSon.getLevelId());
                queryWrapper.orderByDesc("level_num");
                List<LLevelSon> levelSons = ilLevelSonService.list(queryWrapper);
                if(levelSons.size() > 0){
                    LLevelSon levelSon = levelSons.get(0);
                    if(levelSon.getLevelNum() == lLevelSon.getLevelNum()){
                        LLevelUser lLevelUser = new LLevelUser();
                        lLevelUser.setLevelId(lLevelSon.getLevelId());
                        lLevelUser.setUserId(Integer.parseInt(userId));
                        lLevelUser.setCreateTime(new Date());
                        lLevelUser.setState("1");
                        ilLevelUserService.save(lLevelUser);
                    }
                }
            }else {
                lLevelSonUser.setState("2");
                map.put("state","2");
                // 删除考试记录
                answerQueryWrapper = new QueryWrapper<LLevelAnswer>();
                answerQueryWrapper.eq("level_son_id",id);
                answerQueryWrapper.eq("user_id",userId);
                ilLevelAnswerService.remove(answerQueryWrapper);
            }
            ilLevelSonUserService.saveOrUpdate(lLevelSonUser);
            map.put("levelSon",lLevelSon);
            return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
    }

}
